package com.tools.web.interceptor.auth._common;

import com.tools.common.object.Note;

/**
 * 用户多在线记录的 Redis-Lua 脚本接口
 * */
@Note("用户多在线记录的 Redis-Lua 脚本接口")
public interface MultipleRedisLuaScript {

    String GET_AUTH_USER =
            "local key1 = KEYS[1];" +
            "local key2 = KEYS[2];" +
            "if redis.call('exists', key1) == 1 then" +
            "    return redis.call('get', key2);" +
            "else" +
            "    return nil;" +
            "end";

    String SET_AUTH_USER =
            "local keys = redis.call('keys', ARGV[1] .. '*');" +
            "local expiration = tonumber(ARGV[5]);" +
            "if #keys < tonumber(ARGV[2]) then" +
            "    redis.call('setex', ARGV[3], expiration, ARGV[4]);" +
            "else" +
            "    local min_timestamp = math.huge;" +
            "    local min_key = nil;" +
            "    for _, key in ipairs(keys) do" +
            "        local timestamp = tonumber(redis.call('get', key));" +
            "        if timestamp and timestamp < min_timestamp then" +
            "            min_timestamp = timestamp;" +
            "            min_key = key;" +
            "        end" +
            "    end" +
            "    if min_key then" +
            "        redis.call('del', min_key);" +
            "    end" +
            "    redis.call('setex', ARGV[3], expiration, ARGV[4]);" +
            "end" +
            "local ttl = redis.call('ttl', ARGV[6]);" +
            "if ttl <= 0 then" +
            "    redis.call('setex', ARGV[6], expiration, ARGV[7]);" +
            "else" +
            "    redis.call('setex', ARGV[6], ttl + expiration, ARGV[7]);" +
            "end";

    String REMOVE_AUTH_USER =
            "local prefix = ARGV[1];" +
            "local keys = redis.call('keys', prefix .. '*');" +
            "local count = 0;" +
            "for i, key in ipairs(keys) do" +
            "    redis.call('del', key);" +
            "    count = count + 1;" +
            "end" +
            "return count;";



    String UPDATE_AUTH_USER =
            "local key = ARGV[1];" +
            "local newValue = ARGV[2];" +
            "local ttl = redis.call('ttl', key);" +
            "if ttl > 0 then" +
            "    redis.call('setex', key, ttl, newValue);" +
            "    return 1;" +
            "else" +
            "    return 0;" +
            "end";


    String LOGIN_OUT =
            "redis.call('del', ARGV[1]);" +
            "local prefix = ARGV[2];" +
            "local keys = redis.call('keys', prefix .. '*');" +
            "if #keys <= 1 then" +
            "    redis.call('del', ARGV[3]);" +
            "end";
}
